/*
 * Copyright 2008-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.foreveross.bsl.common.utils.page;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Basic {@code Page} implementation.
 * 
 * @param <T> the type of which the page consists.
 * @author Oliver Gierke
 */
public class ExPageImpl<T> implements ExPage<T>, Serializable {

	private static final long serialVersionUID = 867755909294344406L;

	private final List<T> content = new ArrayList<T>();
	private final ExPageable pageable;
	private final long total;

	public static <T> ExPage<T> toPage(List<T> content, Object springDataPage) {
		if (null == springDataPage) {
			throw new IllegalArgumentException(
					"springDataPage must not be null!");
		}
		long total = 0;
		int page = 0;
		int size = 0;
		try {
			{
				Method method = springDataPage.getClass().getDeclaredMethod(
						"getTotalElements", new Class<?>[0]);
				total = ((Number) method.invoke(springDataPage, new Object[0]))
						.longValue();
			}
			{
				Method method = springDataPage.getClass().getDeclaredMethod(
						"getSize", new Class<?>[0]);
				size = ((Number) method.invoke(springDataPage, new Object[0]))
						.intValue();
			}
			{
				Method method = springDataPage.getClass().getDeclaredMethod(
						"getNumber", new Class<?>[0]);
				page = ((Number) method.invoke(springDataPage, new Object[0]))
						.intValue();
			}
		} catch (Exception e) {
			throw new IllegalArgumentException(
					"springDataPage is not the org.springframework.data.domain.Page object!");
		}
		return new ExPageImpl<T>(content, new ExPageRequest(page, size), total);
	}

	/**
	 * Constructor of {@code PageImpl}.
	 * 
	 * @param content the content of this page
	 * @param pageable the paging information
	 * @param total the total amount of items available
	 */
	public ExPageImpl(List<T> content, ExPageable pageable, long total) {

		if (null == content) {
			throw new IllegalArgumentException("Content must not be null!");
		}

		this.content.addAll(content);
		this.total = total;
		this.pageable = pageable;
	}

	/**
	 * Creates a new {@link ExPageImpl} with the given content. This will result in the created {@link ExPage} being identical
	 * to the entire {@link List}.
	 * 
	 * @param content
	 */
	public ExPageImpl(List<T> content) {

		this(content, null, (null == content) ? 0 : content.size());
	}

	public int getNumber() {

		return pageable == null ? 0 : pageable.getPageNumber();
	}

	public int getSize() {

		return pageable == null ? 0 : pageable.getPageSize();
	}

	public int getTotalPages() {

		return getSize() == 0 ? 0 : (int) Math.ceil((double) total
				/ (double) getSize());
	}

	public int getNumberOfElements() {

		return content.size();
	}

	public long getTotalElements() {

		return total;
	}

	public boolean hasPreviousPage() {

		return getNumber() > 0;
	}

	public boolean isFirstPage() {

		return !hasPreviousPage();
	}

	public boolean hasNextPage() {

		return ((getNumber() + 1) * getSize()) < total;
	}

	public boolean isLastPage() {

		return !hasNextPage();
	}

	public Iterator<T> iterator() {

		return content.iterator();
	}

	public List<T> getContent() {

		return Collections.unmodifiableList(content);
	}

	public boolean hasContent() {

		return !content.isEmpty();
	}

	@Override
	public String toString() {

		String contentType = "UNKNOWN";

		if (content.size() > 0) {
			contentType = content.get(0).getClass().getName();
		}

		return String.format("Page %s of %d containing %s instances",
				getNumber(), getTotalPages(), contentType);
	}

	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}

		if (!(obj instanceof ExPageImpl<?>)) {
			return false;
		}

		ExPageImpl<?> that = (ExPageImpl<?>) obj;

		boolean totalEqual = this.total == that.total;
		boolean contentEqual = this.content.equals(that.content);
		boolean pageableEqual = this.pageable == null ? that.pageable == null
				: this.pageable.equals(that.pageable);

		return totalEqual && contentEqual && pageableEqual;
	}

	@Override
	public int hashCode() {

		int result = 17;

		result = 31 * result + (int) (total ^ total >>> 32);
		result = 31 * result + (pageable == null ? 0 : pageable.hashCode());
		result = 31 * result + content.hashCode();

		return result;
	}
}
